package org.study.shardingsphere.boot.controller;

import cn.hutool.json.JSONUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.study.shardingsphere.boot.model.TestModel;
import org.study.shardingsphere.boot.service.TestModelService;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;

/**
 * 类的描述
 *
 * @author Administrator
 * @date 2022-03-09
 */
@Slf4j
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
@RestController
@RequestMapping("/dynamic")
public class TestModelController {
    private final TestModelService testModelService;

    @RequestMapping("/insert")
    public Object dynamicInsertTest() {
        for (int i = 0; i < 3; i++) {
            TestModel testModel = TestModel.builder()
                    .name("insert-sharding")
                    .createTime(new Date())
                    .updateTime(LocalDateTime.now())
                    .build();
            boolean result = testModelService.save(testModel);
            log.info("新增数据结果：{}", result);
        }
        List<TestModel> list = testModelService.list();
        log.info("查询到 {} 条数据", list.size());
        // 验证读操作的负载均衡策略
        list.forEach(item -> {
            TestModel testModel = testModelService.getById(item.getId());
            log.info("当前数据：{}", JSONUtil.toJsonStr(testModel));
        });
        return list;
    }
}
